package huxibianjie.com.lbscandroid.ui.old.fragment;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import huxibianjie.com.lbscandroid.Constants;
import huxibianjie.com.lbscandroid.R;
import huxibianjie.com.lbscandroid.base.BaseFragment;
import huxibianjie.com.lbscandroid.event.ClickEvent;
import huxibianjie.com.lbscandroid.event.LoginEvent;
import huxibianjie.com.lbscandroid.manager.UserManager;
import huxibianjie.com.lbscandroid.model.CountDailyModel;
import huxibianjie.com.lbscandroid.model.ItemModel;
import huxibianjie.com.lbscandroid.model.RankingsModel;
import huxibianjie.com.lbscandroid.model.StepModel;
import huxibianjie.com.lbscandroid.model.UserModel;
import huxibianjie.com.lbscandroid.pedomemter.StepDetector;
import huxibianjie.com.lbscandroid.pedomemter.StepService;
import huxibianjie.com.lbscandroid.task.Callback;
import huxibianjie.com.lbscandroid.task.Task;
import huxibianjie.com.lbscandroid.ui.Service;
import huxibianjie.com.lbscandroid.ui.old.fragment.adapter.HomeAdapter;
import huxibianjie.com.lbscandroid.ui.new_activity.StepListener;
import huxibianjie.com.lbscandroid.util.PrefsUtils;
import huxibianjie.com.lbscandroid.util.StatusBarUtil;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements StepListener, HomeAdapter.OnItemClick {

    private RecyclerView recyclerView;
    private HomeAdapter adapter;
    private long submitStep;//提交过的步数
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            StepService.MyBinder binder = ((StepService.MyBinder) service);
            binder.addStepInterface(HomeFragment.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected int getContentView() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(@NonNull View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getActivity().getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        final LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(null);
        recyclerView.setLayoutManager(manager);

        recyclerView.setAdapter(adapter = new HomeAdapter(getActivity()));
    }

    @Override
    protected void initListener(@NonNull View view) {
        adapter.setItemClick(this);
    }

    private void startService() {
        Intent intent = new Intent(getContext(), StepService.class);
        getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
        getActivity().startService(intent);
    }

    private StepModel stepModel;
    private List<ItemModel> itemModels = new ArrayList<>();

    @Override
    protected void initData(@NonNull View view) {
        showLoading();
        submitStep = PrefsUtils.read(getContext(), Constants.LAST_STEP, 0L);
        stepModel = new StepModel(0, 0);
        itemModels.clear();
        itemModels.add(new ItemModel(ItemModel.Type.ITEM_HOME_TOP, stepModel));
        itemModels.add(new ItemModel(ItemModel.Type.ITEM_HOME_TYPE, ""));
        itemModels.add(new ItemModel(ItemModel.Type.ITEM_HOME_TITLE, ""));
        if (UserManager.getInstance().isLogin()) {
            Task.create(Service.class).getTodayRankings(String.valueOf(UserManager.getInstance().getUserModel().getId())).enqueue(new Callback<RankingsModel>() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onSuccess(@Nullable RankingsModel rankingsModel) {
                    if (rankingsModel != null) {
                        List<RankingsModel.RankingsBean> rankingsBeans = rankingsModel.getRankings();
                        for (int i = 0; i < rankingsBeans.size(); i++) {
                            itemModels.add(new ItemModel(ItemModel.Type.ITEM_HOME_INFO, rankingsBeans.get(i)));
                        }
                        Task.create(Service.class).getHistoryData(String.valueOf(UserManager.getInstance().getUserModel().getId())).enqueue(new Callback<ArrayList<CountDailyModel>>() {
                            @Override
                            public void onSuccess(@Nullable ArrayList<CountDailyModel> arrayList) {
                                if (arrayList != null) {
                                    itemModels.add(new ItemModel(ItemModel.Type.ITEM_HOME_CHART, arrayList));
                                    adapter.replaceAll(itemModels);
                                } else {
                                    itemModels.add(new ItemModel(ItemModel.Type.ITEM_HOME_CHART, ""));
                                    adapter.replaceAll(itemModels);
                                    showToast("获取列表数据失败");
                                }
                                cancelLoading();
                            }

                            @Override
                            public void onFailure(@NonNull String error) {
                                itemModels.add(new ItemModel(ItemModel.Type.ITEM_HOME_CHART, ""));
                                adapter.replaceAll(itemModels);
                                showToast(error);
                                cancelLoading();
                            }
                        });
                    } else {
                        itemModels.add(new ItemModel(ItemModel.Type.ITEM_HOME_CHART, ""));
                        adapter.replaceAll(itemModels);
                        cancelLoading();
                        showToast("获取图表数据失败");
                    }
                }

                @Override
                public void onFailure(@NonNull String error) {
                    itemModels.add(new ItemModel(ItemModel.Type.ITEM_HOME_CHART, ""));
                    adapter.replaceAll(itemModels);
                    cancelLoading();
                    showToast(error);
                }
            });
        }
    }

    @Override
    public void onClickEvent(ClickEvent event) {
        super.onClickEvent(event);
        switch (event.type) {
            case UPDATE_USER_INFO:
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        startService();
    }

    @Override
    public void onLoginEvent(LoginEvent event) {
        super.onLoginEvent(event);
        if (event.isLogin) {
            initData(getView());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unbindService(conn);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            StatusBarUtil.setColor(getActivity(), 0xFFFFFF);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getActivity().getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            }
        }
    }

    @Override
    public void onStepListener(long sumStep) {
        if (Constants.IS_CACHE_STEP) {
            submitStep = sumStep;
            long cacheValue = PrefsUtils.read(getActivity(), Constants.LAST_STEP, 0L);
            if ((submitStep - cacheValue) > 1000) {
                submitStep = cacheValue + 1000;
                PrefsUtils.write(getContext(), Constants.LAST_STEP, submitStep);
            } else {
                PrefsUtils.write(getContext(), Constants.LAST_STEP, submitStep);
            }
            Constants.IS_CACHE_STEP = false;
        }
        stepModel.setSumStep(sumStep);
        long step = sumStep - submitStep;
        if (step < 0) {
            submitStep = 0;
            step = 0;
        }
        stepModel.setStep(step);
        adapter.notifyItemChanged(0);
    }

    private long toTurnStep;

    @Override
    public void toTurn() {
        int permission1 = ActivityCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_COARSE_LOCATION);
        if (permission1 != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    2);
            showToast("如果您没有定位授权，请获取权限，否则无法提交步数信息哦！");
            return;
        }
        toTurnStep = stepModel.getStep();
        if (toTurnStep < Constants.number) {
            showToast("50步以后可提交，五分钟可提交一次，上限为1000步！！！");
            return;
        }
        if (toTurnStep > 1000) {
            toTurnStep = 1000;
        }
        if (!UserManager.getInstance().isLogin()) return;
        showLoading();
        String ids = String.valueOf(UserManager.getInstance().getUserModel().getId());
        Task.create(Service.class).submitStep(ids, toTurnStep).enqueue(new Callback<Map<String, String>>() {
            @Override
            public void onSuccess(@Nullable Map<String, String> mapData) {
                if (mapData != null) {
                    showToast("当前位置信息打包成功！");
                    UserModel userModel = UserManager.getInstance().getUserModel();
                    userModel.setTodayCurrency(mapData.containsKey("todayCurrency") ? Integer.parseInt(mapData.get("todayCurrency"))
                            : userModel.getTodayCurrency());
                    userModel.setTaskCurrency(mapData.containsKey("taskCurrency") ? Integer.parseInt(mapData.get("taskCurrency"))
                            : userModel.getTaskCurrency());
                    userModel.setMoney(mapData.containsKey("money") ? Integer.parseInt(mapData.get("money"))
                            : userModel.getMoney());
                    userModel.setTotalAassets(mapData.containsKey("totalAassets") ? Integer.parseInt(mapData.get("totalAassets"))
                            : userModel.getTotalAassets());
                    UserManager.getInstance().save(userModel, false);
                    HashMap<String, String> map = new HashMap<>();
                    map.put("phone", UserManager.getInstance().getUserModel().getPhone());
                    map.put("stepnumber", String.valueOf(toTurnStep));
                    MobclickAgent.onEvent(getContext(), "Withdrawmoney", map);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Constants.IS_CACHE_STEP = true;
                            onStepListener(StepDetector.CURRENT_STEP);
                        }
                    }, 500);
                } else {
                    showToast("提步失败");
                }
                cancelLoading();
            }

            @Override
            public void onFailure(@NonNull String error) {
                showToast(error);
                cancelLoading();
            }
        });
    }
}
